package com.lkd.handler;

import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
@Slf4j
public class OrderDelayCloseHandler implements MsgHandler {
    @Autowired
    private OrderService orderService;
    @Autowired
    private WxPayTemplate wxPayTemplate;

    @Override
    public void process(String jsonMsg) throws IOException {

        if(StringUtils.isEmpty(jsonMsg)){
            log.error(TopicConfig.ORDER_CHECK_TOPIC + "消息内容为空");
            return;
        }

        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        String orderNo = orderCheck.getOrderNo();
        //1.获取订单数据
        if(StringUtils.isEmpty(orderNo)){
            log.error(TopicConfig.ORDER_CHECK_TOPIC + "参数有误" + jsonMsg);
            return;
        }
        OrderEntity orderEntity = orderService.getByOrderNo(orderNo);
        if(orderEntity == null){
            log.error("延迟取消订单，订单编号不存在" + orderNo);
            return;
        }

        //2.判断订单是否已经支付，如果没有支付修改状态为已取消
        if(orderEntity.getStatus().equals(VMSystem.ORDER_STATUS_CREATE)){
            orderEntity.setStatus(VMSystem.ORDER_STATUS_INVALID);
            orderService.updateById(orderEntity);
            //让二维码失效
            WxPayParam param = new WxPayParam();
            param.setOutTradeNo(orderNo);
            try {
                this.wxPayTemplate.closeOrder(param);
            } catch (Exception e) {
                log.error("关闭微信支付单失败",e);
            }
        }

    }
}
